package com.gitee.huxing.practice;

import java.util.LinkedList;
import java.util.Random;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description:
 * @ProjectName: algorithmicPactice
 * @Package: HashMapPerformance
 * @ClassName: HashMapPerformance
 * @Author: huxingmale
 * @DateTime: 2022-05-10 11:01
 */
public class HashMapPerformance {

    public static int ITERATION_COUNT = 10000000;

    private static AtomicInteger exitThreadCount = new AtomicInteger(0);

    public static Hashtable<Integer, Integer> myHashMap;

    public static void initData(){
        myHashMap = new Hashtable<>(1000);
        for (int counter = 0; counter < 1000; counter++){
            myHashMap.put(counter, counter);
        }
    }

    private static class Writer extends Thread{
        @Override
        public void run() {
            Random random = new Random();
            for (int iteration = 0; iteration < ITERATION_COUNT; ++iteration){
                int counter = random.nextInt(1000 - 1);
                myHashMap.put(counter, counter);
            }
            exitThreadCount.incrementAndGet();
        }
    }

    private static class Reader extends Thread{
        @Override
        public void run() {
            Random random = new Random();
            for (int iteration = 0; iteration < ITERATION_COUNT; ++iteration) {
                int counter = random.nextInt(1000 - 1);
                myHashMap.get(counter);
            }
            exitThreadCount.incrementAndGet();
        }
    }

    public static void main(String[] args) throws Exception{
        initData();
        long start = System.currentTimeMillis();

        // Create 10 Writer Threads
        for (int counter = 0; counter < 10; ++counter){
            new Writer().start();
        }

        // Create 10 Reader Threads
        for (int counter = 0; counter < 10; ++counter){
            new Reader().start();
        }

        // Wait for all threads to complete
        while (exitThreadCount.get() < 20) {
            Thread.sleep(100);
        }
        System.out.println("Total execution Time(ms): " + (System.currentTimeMillis() - start) );
    }
}
